/*
 * 广州云徙科技有限公司源代码，版权归广州云徙科技有限公司所有。
 * 
 * 项目名称 : yxs-gateway
 * 创建日期 : 2017年3月28日
 * 修改历史 : 
 *     1. [2017年3月28日]创建文件 by tan.wenjuan
 */
package com.project.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.NotEmpty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.dtyunxi.rest.PageData;
import com.dtyunxi.rest.RestCode;
import com.dtyunxi.rest.RestResponse;
import com.dtyunxi.util.DateUtil;
import com.project.common.Constants;
import com.project.entity.activity.Activity;
import com.project.entity.activity.ActivityUser;
import com.project.entity.enumcommon.ActivityAuditStatusEnum;
import com.project.entity.enumcommon.UserTypeEnum;
import com.project.entity.user.User;
import com.project.service.IActivityService;
import com.project.service.IActivityUserService;
import com.project.service.IAreaService;
import com.project.service.IUserActivityService;
import com.project.service.IUserService;
import com.project.util.AutoSetVoValue;
import com.project.util.BaseService;
import com.project.util.BeanCopyUtil;
import com.project.util.EhcacheUtil;
import com.project.util.LoginUserUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

/**
 * 活动管理
 * @author tan.wenjuan
 */
@RestController
@RequestMapping("api/activity")
@Api(value = "api/activity", description = "活动管理")
public class ActivityController {
    
	private static final Logger logger = LoggerFactory.getLogger(ActivityController.class);
	
	@Autowired
    private IActivityService activityService;
	
	@Autowired
	private IActivityUserService activityUserService;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
    private IAreaService areaService;
	
	
	@Autowired
	private IUserActivityService userActivityService;
	
    @ApiOperation(value = "活动列表v0.1.0", notes = "活动列表v0.1.0", response = Activity.class, responseContainer = "List", tags = {"活动管理", })
	@ApiResponses(value = { @ApiResponse(code = 200, message = "活动列表", response = Activity.class) })
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public RestResponse activityList(@RequestParam(defaultValue = "1", required = false) int pageNo,
            @RequestParam(defaultValue = "5", required = false) int pageSize){
        PageData page = new PageData();
        Activity activity = new Activity();
        List<Activity> list = activityService.queryPageData(activity, pageSize, pageNo);
        int total = activityService.queryCount(activity);
        page = BaseService.listVoToPageData(pageNo, pageSize, list, total);
        
        return new RestResponse(page);
    }
    
    @ApiOperation(value = "活动详情v0.1.0", notes = "活动详情v0.1.0", response = Activity.class, tags = {"活动管理", })
    @ApiResponses(value = { @ApiResponse(code = 200, message = "活动详情", response = Activity.class) })
    @RequestMapping(value = "ops/{id}", method = RequestMethod.GET)
    public RestResponse activityDetail(@ApiParam(required = true, name = "id", value = "id") @PathVariable Long id,
            HttpServletRequest request, HttpServletResponse response){
    	User user = LoginUserUtil.getLoginUser(request, response);
//user = userService.getById(51L);//测试的时候使用（测试完之后清除掉）
    	Activity activity = new Activity();
    	if(user==null){
    	    activity = activityService.queryById(id, null);
        }else{
        	Long userId = user.getId();
        	activity = activityService.queryById(id, userId);
        }
    	if(activity!=null){
    	    if (StringUtils.isNotEmpty(activity.getProvince()))
                activity.setProvince(areaService.getAreaNameByCode(activity.getProvince()));
            if (StringUtils.isNotEmpty(activity.getCity()))
                activity.setCity(areaService.getAreaNameByCode(activity.getCity()));
            if (StringUtils.isNotEmpty(activity.getDistrict()))
                activity.setDistrict(areaService.getAreaNameByCode(activity.getDistrict()));
    	}
        return new RestResponse(activity);
    }
    
    @ApiOperation(value = "活动报名v0.1.0", notes = "活动报名v0.1.0", response = RestResponse.class, tags = {"活动管理", })
    @ApiResponses(value = { @ApiResponse(code = 200, message = "活动报名", response = RestResponse.class) })
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public RestResponse activityRegister(@ApiParam(required = true, name = "id", value = "活动id") @RequestParam(value = "id", required = true) Long id,
            @ApiParam(required = true, name="name",value="姓名")@NotEmpty(message = "姓名不能为空") @RequestParam(value = "name", required = true) String name,
            @ApiParam(required = true, name="mobile",value="手机号")@NotEmpty(message = "手机号不能为空") @RequestParam(value = "mobile", required = true) String mobile,
            @ApiParam(required = true, name="email",value="邮箱")@NotEmpty(message = "邮箱不能为空") @RequestParam(value = "email", required = true) String email,
            @ApiParam(required = false, name="province",value="省级code") @RequestParam(value = "province", required = false) String province,
            @ApiParam(required = false, name="city",value="市级code") @RequestParam(value = "city", required = false) String city,
            @ApiParam(required = false, name="district",value="区code")@RequestParam(value = "district", required = false) String district,
            @ApiParam(required = true, name="company",value="公司")@NotEmpty(message = "公司不能为空") @RequestParam(value = "company", required = true) String company,
            @ApiParam(required = true, name="job",value="职务")@NotEmpty(message = "职务不能为空") @RequestParam(value = "job", required = true) String job,
            @ApiParam(required = false, name="strongPoint",value="擅长领域") @RequestParam(value = "strongPoint", required = false) String strongPoint,
            @ApiParam(required = false, name="honor",value="荣誉") @RequestParam(value = "honor", required = false) String honor,
            @ApiParam(required = false, name="product",value="著作")@RequestParam(value = "product", required = false) String product,
            @ApiParam(required = false, name="ability",value="能力/经验") @RequestParam(value = "ability", required = false) String ability,
            HttpSession session, HttpServletRequest request){
        User user = (User)session.getAttribute(Constants.CURRENT_LOGIN_USER);
        //判断报名时间
        Activity activity = activityService.getById(id);
        logger.info("系统时间:{},time:{}", DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        boolean allowRegistration = activity!=null && DateUtil.isBetweenDateByClosedInterval(activity.getRegistrationStartTime(), activity.getRegistrationEndTime());
        if(!allowRegistration){
        	return new RestResponse(RestCode.RESULT_SYSTEM_ERROR,"报名已截止");
        }
      //每个账号只能报名一次
		int count = activityUserService.checkUserRepetitionApply(id, user.getUserCode());
		if(count > 0) {
			return new RestResponse(RestCode.RESULT_SYSTEM_ERROR,"每个账号只能报名一次");
		}
		//保存活动用户信息
        ActivityUser activityUser = new ActivityUser();
        activityUser.setActivityId(id);
        activityUser.setName(name);
        activityUser.setMobile(mobile);
        activityUser.setEmail(email);
        activityUser.setProvince(province);
        activityUser.setCity(city);
        activityUser.setDistrict(district);
        activityUser.setCompany(company);
        activityUser.setPosition(job);
        activityUser.setAdeptField(strongPoint);
        activityUser.setHonor(honor);
        activityUser.setWritings(product);
        activityUser.setIntro(ability);
        activityUser.setUserId(user.getId());
        activityUser.setUserCode(user.getUserCode());
        activityUser.setAuditStatus(ActivityAuditStatusEnum.DEFAULT.getValue());//待审核
        activityUser.setApplicationTime(new Date());
        activityUserService.save(activityUser);
        
        //保存数据到用户活动中间表
        userActivityService.save(user.getId(), id);
        //没有入会，且第一次报名，更新个人信息
        if(UserTypeEnum.REGISTERED.getValue().equals(user.getUserType())){
        	ActivityUser entity = new ActivityUser();
        	entity.setUserId(user.getId());
        	List<ActivityUser> list = activityUserService.findList(entity);
        	if(list.size()==1){
        		User u = new User();
        		BeanCopyUtil.copyPropertiesIgnoreNull(u, user);
        		try {
        			u = AutoSetVoValue.autoSetValuePlugn(
        					User.class, 
        					new String[]{"email", "province",
        							"city", "district", "company", "position", "adeptField",
        							"honor", "writings", "intro", "name"}, 
        					new Object[]{email, province, 
        							city, district, company, job, strongPoint,
        							honor, product, ability, name});
        			u.setId(user.getId());
        			userService.update(u);
        			logger.info("------------------activityRegister活动报名.user:{}", u);
        			User newUser = userService.getById(user.getId());
        			String auth = request.getHeader("auth");
        			logger.info("------------------activityRegister活动报名.更新缓存auth:{}", auth);
        			EhcacheUtil.put(Constants.LOGIN_USER_CACHE, auth, newUser);
        			request.getSession().setAttribute(Constants.CURRENT_LOGIN_USER, newUser);
        		} catch (Exception e) {
        			logger.error(e.getMessage(),e);
        			return new RestResponse(RestCode.RESULT_SYSTEM_ERROR,"更新个人信息失败");
        		}
        	}
        }
		return RestResponse.SUCCESS;
		
        /*
        if(user==null){
            return new RestResponse(1,"请先登录！");
        }else{
        	RestResponse restResponse = new RestResponse(0,"操作成功！");
        	try {
        		Long userId = user.getId();
        		String userCode = user.getUserCode();//用户账号
        		if(StringUtils.isBlank(userCode)) {
        			userCode = "0";
        		}
        		
        		//若是注册用户，填写后的内容更新到个人信息，若是申请为会员（包括待审核、已通过、未通过）则不更新个人信息；
        		if(UserTypeEnum.REGISTERED.getValue().equals(user.getUserType())) {
        			User u = new User();
        			BeanCopyUtil.copyPropertiesIgnoreNull(u, user);
        			u = AutoSetVoValue.autoSetValuePlugn(
        				User.class, 
	                	new String[]{"email", "province", 
	                				"city", "district", "company", "position", "adeptField",
	                				"honor", "writings", "intro", "name"}, 
	                	new Object[]{email, province,
	                				city, municipality, company, job, strongPoint,
	                				honor, product, ability, name});
        			u.setId(userId);
        			userService.update(u);
        			String auth = request.getHeader("auth");
        			logger.info("------------------activityRegister活动报名.更新缓存auth:{}", auth);
        			EhcacheUtil.put(Constants.LOGIN_USER_CACHE, auth, user);
        			request.getSession().setAttribute(Constants.CURRENT_LOGIN_USER, user);
        		} else if(UserTypeEnum.MEMBER.equals(user.getUserType())) {
        			Member member = new Member();
        			BeanCopyUtil.copyPropertiesIgnoreNull(member, user);
        			member = AutoSetVoValue.autoSetValuePlugn(
	        			Member.class, 
	                	new String[]{"auditStatus", "userType", "mobile", "email", "province", 
	                				"city", "district", "company", "position", "adeptField",
	                				"honor", "writings", "intro", "name", "userId",
	                				"applicationTime", "userCode"}, 
	                	new Object[]{"0", UserTypeEnum.MEMBER, mobile, email, province,
	                				city, municipality, company, job, strongPoint,
	                				honor, product, ability, name, userId,
	                				new Date(), userCode});
        			memberService.update(member);
        		}
        		
        		//对参加该活动的手机号进行查重，若是已有手机号参加该活动，提示该手机号已被使用
        		int count = activityUserService.checkRepetitionApply(id, mobile);
        		if(count > 0) {
        			return new RestResponse(1,"该手机号已被使用！");
        		}
        		
        		//每个账号只能报名一次
        		count = activityUserService.checkUserRepetitionApply(id, userCode);
        		if(count > 0) {
        			return new RestResponse(1,"每个账号只能报名一次！");
        		}
        		
                //保存活动用户信息
                ActivityUser activityUser = new ActivityUser();
                activityUser = AutoSetVoValue.autoSetValuePlugn(
                	ActivityUser.class, 
                	new String[]{"activityId", "name", "mobile", "email", "province", 
                				"city", "district", "company", "position", "adeptField",
                				"honor", "writings", "intro", "userId", "userCode"}, 
                	new Object[]{id, name, mobile, email, province,
                				city, municipality, company, job, strongPoint,
                				honor, product, ability, userId, userCode});
                activityUser.setActivityId(id);
                activityUser.setName(name);
                activityUser.setMobile(mobile);
                activityUser.setEmail(email);
                activityUser.setProvince(province);
                activityUser.setCity(city);
                activityUser.setDistrict(municipality);
                activityUser.setCompany(company);
                activityUser.setPosition(job);
                activityUser.setAdeptField(strongPoint);
                activityUser.setHonor(honor);
                activityUser.setWritings(product);
                activityUser.setIntro(ability);
                activityUser.setUserId(userId);
                activityUser.setUserCode(userCode);
                activityUser.setAuditStatus(ActivityAuditStatusEnum.DEFAULT.getValue());//待审核
                //activityUserService.save(activityUser);
                activityUserService.saveActivityUser(activityUser);
                
                //保存数据到用户活动中间表
                userActivityService.save(userId, id);
			} catch (Exception e) {
				restResponse = new RestResponse(0, "系统内部错误！");
				logger.info(e.getMessage(), e);
			}
        	return restResponse;
        }*/
    }

	@ApiOperation(value = "取消活动v0.1.0", notes = "取消活动v0.1.0", response = RestResponse.class, tags = {"活动管理", })
    @ApiResponses(value = { @ApiResponse(code = 200, message = "取消活动", response = RestResponse.class) })
    @RequestMapping(value = "/cancel", method = RequestMethod.POST)
    public RestResponse activityCancel(HttpSession session,@ApiParam(required = true, name = "id", value = "id") Long id,
    		 @ApiParam(required = false, name="cancelReason",value="取消原因") @RequestParam(value = "cancelReason", required = false) String cancelReason){
	    User user = (User)session.getAttribute(Constants.CURRENT_LOGIN_USER);
	    if(user==null){
	        return new RestResponse(1,"请先登录！");
	    }else{
	        boolean bln = activityUserService.activityCancel(user.getId(),id, cancelReason);
	        if(bln) {
	            return new RestResponse(0,"操作成功！");         
	        } else {
	            return new RestResponse(1,"操作失败！");
	        }
	    }
    }
    
    @ApiOperation(value = "个人活动列表v0.1.0", notes = "个人活动列表v0.1.0",response = ActivityUser.class, responseContainer = "List", tags = {"活动管理", })
    @ApiResponses(value = { @ApiResponse(code = 200, message = "个人活动列表", response = ActivityUser.class) })
    @RequestMapping(value = "/listByUser", method = RequestMethod.GET)
    public RestResponse activityListByUser(HttpSession session,
    		@RequestParam(value = "auditStatus", required = false) String auditStatus,
    		@RequestParam(value = "status", required = false) String status,
    		@RequestParam(defaultValue = "1", required = false) int pageNo,
            @RequestParam(defaultValue = "5", required = false) int pageSize) {
        User user = (User)session.getAttribute(Constants.CURRENT_LOGIN_USER);
        //根据userId查询活动列表
        Long userId = user.getId();
        
        //List<ActivityUser> activityUserList = activityUserService.queryByUserId(userId);
        List<ActivityUser> activityUserList = activityUserService.queryByUserIdAndStatus(userId, auditStatus, status, pageNo, pageSize);
        
        return new RestResponse(activityUserList);
    }
}
